package com.renjun.smweb.controller.AdminController;

import com.alibaba.fastjson.JSONObject;
import com.renjun.smweb.annotation.AuthorityDeclaration;
import com.renjun.smweb.commons.global.StaticCaches;
import com.renjun.smweb.commons.util.ResponseUtils;
import com.renjun.smweb.dao.pojo.LoginInfo;
import com.renjun.smweb.service.AdminService.AdminService;
import com.renjun.smweb.exceptions.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;

/**
 * Created by huamin on 2017/2/21.
 * 用户管理M4
 */
@Controller
@RequestMapping("/adminmgr")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    @AuthorityDeclaration(id = "M4-11", desc = "登录",reqParam = "ename,pwd,vcode",resBody = "id ,roleid ,username ,realname ,opername ,operid ,roletype ,schoolcode ,districtcode ,deleted ,currentURL ,currentURLName ,pwdstatus ",errMsgs = "sql异常,业务处理失败")
    public JSONObject login(HttpServletRequest request) {
        //load root path
        StaticCaches.setRealRootPath(request.getServletContext().getRealPath("/"));
        JSONObject rs = ResponseUtils.createErrorResponseBody(null);
        Map<String, Object> params = ResponseUtils.createRequestParamsMap(request);
        try {
            rs = adminService.login(params,request);
        } catch ( SQLException | BaseException e) {
            e.printStackTrace();
       //     rs.put("message", e.getMessage());
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        }
        return rs;
    }

    /**
     * 用户列表
     * @param request {areaid:""deleted:""limit:10mobile:""offset:0order:"asc"roletype:""schoolid:""sfzjh:""sort:"username"xm:""}
     * @return [{"ename":"xuexiao","districtid":"310101","rolename":"学校管理员","schoolid":"b4f4c81e-10b5-43a4-b2d8-af21865a8204","roletype":"3","id":"3871FB7F096F9190E050A8C0080F4D1A","schoolname":"bbb学校","realname":"学校级测试"}]
     */
    @RequestMapping(value = "/adminUserList", method = RequestMethod.POST)
    @ResponseBody
    @AuthorityDeclaration(id = "M4-1", desc = "用户列表",errMsgs = "找不到相应的数据",reqParam = "{'sort':'排序字段','order':'排序方式','offset':'当前页','limit':'页面条数','districtcode':'区县code','schoolcode':'学校code','xm':'姓名','sfzjh':'身份证件号','mobile':'手机号码','roletype':'角色类型','deleted':'删除位'}",resBody = "{'total':199,'data':[{'sfzjh':身份证件号,'rolename':'角色名称','mobile':'手机号码','schoolname':'学校名称','realname':'用户真实姓名','total':'总记录数','ename':'用户名','deleted':'删除位','districtcode':'区县code','addtime':'添加时间','schoolcode':'学校code','roletype':'角色类别','id':'用户id','rn':'显示记录数','email':'邮箱'}],'message':'done','status':'响应状态'}")
    public JSONObject adminUserList(HttpServletRequest request, HttpServletResponse response) {
        JSONObject rs = ResponseUtils.createErrorResponseBody(null);
        Map<String, Object> params = ResponseUtils.createRequestAndSessionLoginInfo(request);
        try {
            rs = adminService.queryAdminUserList(params);
        } catch (SQLException | DataNotFoundException e) {
            e.printStackTrace();
           // rs.put("message", e.getMessage());
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        }
        return rs;
    }

    @RequestMapping(value = "/expAdminUserList", method = RequestMethod.POST)
    @ResponseBody
    @AuthorityDeclaration(id = "M4-10", desc = "用户列表导出",errMsgs = "找不到相应的数据,Excel文件解析错误,没有找到对应的文件类型",reqParam = "'sort':'排序字段','order':'排序方式','offset':'当前页','limit':'页面条数','districtcode':'区县code','schoolcode':'学校code','xm':'姓名','sfzjh':'身份证件号','mobile':'手机号码','roletype':'角色类型','deleted':'删除位'",resBody = "{'data':{'url':'下载地址'},'message':'返回信息','status':'响应状态'}")
    public JSONObject expAdminUserList(HttpServletRequest request, HttpServletResponse response) {
        JSONObject rs = ResponseUtils.createErrorResponseBody(null);
        Map<String, Object> params = ResponseUtils.createRequestAndSessionLoginInfo(request);
        try {
            rs = adminService.expAdminUserList(params);
        } catch (SQLException |  IOException | DataNotFoundException |FileTypeNotFoundException e) {
            e.printStackTrace();
        //    rs.put("message", e.getMessage());
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        }
        return rs;
    }

    /**
     * 用户管理-查看用户信息
     * @param request {id:"3871FB7F096F9190E050A8C0080F4D1A"}
     * @return [{"ename":"xuexiao","districtid":"310101","roleid":"4","schoolid":"b4f4c81e-10b5-43a4-b2d8-af21865a8204","id":"3871FB7F096F9190E050A8C0080F4D1A","pwd":"123456","realname":"学校级测试"}]
     */
    @RequestMapping(value = "/showAdminUser", method = RequestMethod.POST)
    @ResponseBody
    @AuthorityDeclaration(id = "M4-4", desc = "用户管理-查看用户信息",errMsgs = "找不到相应的数据",reqParam = "{'id':'用户id'}",resBody = "{'data':{'sfzjh':身份证件号,'roleid':'角色id','remark':'备注','updateuserid':'更新人id','lastlogintime':'最后登录时间','deletedtime':'删除时间','districtcode':'区县code','roletype':'角色类别','id':'用户id','email':'邮箱','logintime':登录时间,'rolename':'角色名称','mobile':'手机号码','realname':真实姓名,'logincnt':'登录次数 默认0','ename':'用户名','deleted':'删除位','ciphertextmd':'密码密文','addtime':添加时间,'schoolcode':'学校code','adduserid':'添加人id','updatetime':'更新时间','ciphertext':'密码明文'},'message':'返回信息','status':'响应状态'}")
    public JSONObject showAdminUser(HttpServletRequest request, HttpServletResponse response) {
        JSONObject rs = ResponseUtils.createErrorResponseBody(null);
        Map<String, Object> params = ResponseUtils.createRequestAndSessionLoginInfo(request);
        try {
            rs = adminService.queryAdminUserInformation(params);
        } catch (SQLException | DataNotFoundException e) {
            e.printStackTrace();
      //      rs.put("message", e.getMessage());
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        }
        return rs;
    }

    /**
     * 用户修改
     * @param request {areaid:""deleted:""districtid:""email:""ename:""mobile:""realname:""roleid:""roletype:""schoolid:""sfzjh:""}
     * @return []
     */
    @RequestMapping(value = "/updateAdminUser", method = RequestMethod.POST)
    @ResponseBody
    @AuthorityDeclaration(id = "M4-3", desc = "用户修改",errMsgs = "邮箱重复,手机号码重复,身份证件号重复,找不到相应的数据,系统超时请重新登录",reqParam = "{'sfzjh':身份证件号,'roleid':'角色id','remark':'备注','updateuserid':'更新人id','lastlogintime':'最后登录时间','deletedtime':'删除时间','districtcode':'区县code','roletype':'角色类别','id':'用户id','email':'邮箱','logintime':登录时间,'rolename':'角色名称','mobile':'手机号码','realname':真实姓名,'logincnt':'登录次数 默认0','ename':'用户名','deleted':'删除位','ciphertextmd':'密码密文','addtime':添加时间,'schoolcode':'学校code','adduserid':'添加人id','updatetime':'更新时间','ciphertext':'密码明文'}",resBody = "{'message':'修改成功','status':'响应状态'}")
    public JSONObject updateAdminUser(HttpServletRequest request, HttpServletResponse response) {
        JSONObject rs = ResponseUtils.createErrorResponseBody(null);
        Map<String, Object> params = ResponseUtils.createRequestAndSessionLoginInfo(request);
        LoginInfo loginInfo = (LoginInfo) request.getSession().getAttribute("userinfo");
        try {
            if(loginInfo==null)throw new SystemTimeOutException();
            params.put("adminid",loginInfo.getId());
            rs = adminService.updateUserInformation(params);
        } catch (SQLException | ValidateSameEmailException | ValidateSameMobileException | ValidateSameSfzjhException | DataNotFoundException | SystemTimeOutException e) {
            e.printStackTrace();
        //    rs.put("message", e.getMessage());
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        } catch (DistrictIdException e) {
            e.printStackTrace();
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        } catch (BaseException e) {
            e.printStackTrace();
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        }
        return rs;
    }

    @RequestMapping(value = "/addAdminUser", method = RequestMethod.POST)
    @ResponseBody
    @AuthorityDeclaration(id = "M4-2", desc = "新增用户",errMsgs = "没有找到对应的字典,用户名不能重复,请重新输入用户名,邮箱重复,手机号码重复,身份证件号重复,找不到相应的数据",reqParam = "{'roletype':'角色类别','roleid':'角色id','districtcode':'区县code','schoolcode':'学校code','realname':'真实姓名','ename':'用户名','sfzjh':'身份证件号','mobile':'手机号码','email':'邮箱'}",resBody = "{'message':'添加用户成功','status':'响应状态'}")
    public JSONObject addAdminUser(HttpServletRequest request, HttpServletResponse response) {
        JSONObject rs = ResponseUtils.createErrorResponseBody(null);
        Map<String, Object> params = ResponseUtils.createRequestAndSessionLoginInfo(request);
        LoginInfo loginInfo = (LoginInfo) request.getSession().getAttribute("userinfo");
        try {
            if(loginInfo==null)throw new SystemTimeOutException();
            params.put("adminid",loginInfo.getId());
            rs = adminService.addAdminUser(params);
        } catch (DictIsNotFoundException | DistrictIdException | UserNameException | SQLException | ValidateSameEmailException | ValidateSameMobileException | ValidateSameSfzjhException | DataNotFoundException | SystemTimeOutException e) {
            e.printStackTrace();
     //       rs.put("message", e.getMessage());
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        }
        return rs;
    }

    @RequestMapping(value = "/delAdminUser", method = RequestMethod.POST)
    @ResponseBody
    @AuthorityDeclaration(id = "M4-5", desc = "用户注销",errMsgs = "没有找到对应的字典,找不到相应的数据,系统超时请重新登录",reqParam = "{'id':'用户id'}",resBody = "{'message':'注销成功','status':'响应状态'}")
    public JSONObject delAdminUser(HttpServletRequest request, HttpServletResponse response) {
        JSONObject rs = ResponseUtils.createErrorResponseBody(null);
        Map<String, Object> params = ResponseUtils.createRequestAndSessionLoginInfo(request);
        LoginInfo loginInfo = (LoginInfo) request.getSession().getAttribute("userinfo");
        try {
            if(loginInfo==null)throw new SystemTimeOutException();
            params.put("adminid",loginInfo.getId());
            rs = adminService.cancelAdminUser(params);
        } catch (DistrictIdException | SQLException | DataNotFoundException | SystemTimeOutException e) {
            e.printStackTrace();
         //   rs.put("message", e.getMessage());
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        }
        return rs;
    }

    @RequestMapping(value = "/regainAdminUser", method = RequestMethod.POST)
    @ResponseBody
    @AuthorityDeclaration(id = "M4-6", desc = "用户恢复",errMsgs = "没有找到对应的字典,找不到相应的数据,系统超时请重新登录",reqParam = "{'id':'用户id'}",resBody = "{'message':'恢复成功','status':'响应状态'}")
    public JSONObject regainAdminUser(HttpServletRequest request, HttpServletResponse response) {
        JSONObject rs = ResponseUtils.createErrorResponseBody(null);
        Map<String, Object> params = ResponseUtils.createRequestAndSessionLoginInfo(request);
        LoginInfo loginInfo = (LoginInfo) request.getSession().getAttribute("userinfo");
        try {
            if(loginInfo==null)throw new SystemTimeOutException();
            params.put("adminid",loginInfo.getId());
            rs = adminService.recoveryAdminUser(params);
        } catch (DistrictIdException | SQLException | DataNotFoundException | SystemTimeOutException e) {
            e.printStackTrace();
        //    rs.put("message", e.getMessage());
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        } catch (BaseException e) {
            e.printStackTrace();
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        }
        return rs;
    }

    //清除用户管理员邮箱
    @RequestMapping(value = "/clearUserEmail", method = RequestMethod.POST)
    @ResponseBody
    @AuthorityDeclaration(id = "M4-9", desc = "清除用户管理员邮箱",errMsgs = "找不到相应的数据,系统超时请重新登录",reqParam = "{'id':'用户id'}",resBody = "{'message':'清除用户邮箱成功','status':'响应状态'}")
    public JSONObject clearUserEmail(HttpServletRequest request, HttpServletResponse response) throws DictIsNotFoundException {
        Map<String, Object> map = ResponseUtils.createRequestAndSessionLoginInfo(request);
        JSONObject rs = ResponseUtils.createErrorResponseBody(null);
        LoginInfo loginInfo = (LoginInfo) request.getSession().getAttribute("userinfo");
        try {
            if(loginInfo==null)throw new SystemTimeOutException();
            map.put("adminid",loginInfo.getId());
            rs = adminService.clearUserEmail(map);
        } catch (SQLException | DataNotFoundException | SystemTimeOutException e) {
            e.printStackTrace();
        //    rs.put("message", e.getMessage());
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        }
        return rs;
    }

    //重置用户管理员密码
    @RequestMapping(value = "/recoverUserPwd", method = RequestMethod.POST)
    @ResponseBody
    @AuthorityDeclaration(id = "M4-8", desc = "重置用户管理员密码",errMsgs = "找不到相应的数据,系统超时请重新登录",reqParam = "{'id':'用户id'}",resBody = "{'message':'返回信息','status':'响应状态'}")
    public JSONObject recoverUserPwd(HttpServletRequest request, HttpServletResponse response) throws DictIsNotFoundException {
        Map<String, Object> map = ResponseUtils.createRequestAndSessionLoginInfo(request);
        JSONObject rs = ResponseUtils.createErrorResponseBody(null);
        LoginInfo loginInfo = (LoginInfo) request.getSession().getAttribute("userinfo");
        try {
            if(loginInfo==null)throw new SystemTimeOutException();
            map.put("adminid",loginInfo.getId());
            rs = adminService.recoverUserPwd(map);
        } catch (SQLException | DataNotFoundException|SystemTimeOutException e) {
            e.printStackTrace();
       //     rs.put("message", e.getMessage());
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        }
        return rs;
    }


    //修改用户管理员密码
    @RequestMapping(value = "/modifyAdminPwd", method = RequestMethod.POST)
    @ResponseBody
    @AuthorityDeclaration(id = "M4-7", desc = "修改管理员密码",errMsgs = "找不到相应的数据,系统超时请重新登录,初始密码不一致不能进行修改",reqParam = "{'adminid':'管理员id','oldpwd':'原始密码','newpwd':'新密码'}",resBody = "{'message':'返回信息','status':'响应状态'}")
    public JSONObject modifyAdminPwd(HttpServletRequest request, HttpServletResponse response) throws DictIsNotFoundException {
        Map<String, Object> map = ResponseUtils.createRequestAndSessionLoginInfo(request);
        JSONObject rs = ResponseUtils.createErrorResponseBody(null);
        HttpSession session = request.getSession();
        LoginInfo loginInfo = (LoginInfo) session.getAttribute("userinfo");
        try {
            if(loginInfo == null)throw new SystemTimeOutException();
            map.put("adminid",loginInfo.getId());
            rs = adminService.modifyAdminPwd(map);
        } catch (SQLException | DataNotFoundException | LaunchCommitException | SystemTimeOutException e) {
            e.printStackTrace();
        //    rs.put("message", e.getMessage());
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        } catch (PasswordSameException e) {
            e.printStackTrace();
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        }
        return rs;
    }

    @RequestMapping(value = "/getShowRoleList", method = RequestMethod.POST)
    @ResponseBody
    @AuthorityDeclaration(id = "getShowRoleList", desc = "根据角色类型获取角色",reqParam = "roletype",resBody = "districtcode,roleid,roletype,rolename",errMsgs = "sql异常,找不到对应数据")
    public JSONObject getShowRoleList(HttpServletRequest request) {
        JSONObject rs = ResponseUtils.createErrorResponseBody(null);
        Map<String, Object> map = ResponseUtils.createRequestAndSessionLoginInfo(request);
        try {
            rs = adminService.getRoleByRoleType(map);
        } catch (SQLException | DataNotFoundException e) {
            e.printStackTrace();
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        }
        return rs;
    }
}
